package com.wlb365.admin.modules;

import cn.hutool.core.util.StrUtil;
import com.wlb365.admin.common.constants.Constants;
import com.wlb365.admin.common.constants.UploadPathEnum;
import com.wlb365.admin.common.dto.R;
import com.wlb365.admin.common.exception.AdminException;
import com.wlb365.admin.common.utils.FileUploadKit;
import com.wlb365.admin.common.utils.HttpServletContextKit;
import com.wlb365.admin.modules.sys.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * 通用controoler.
 *
 * @author zwh
 * @version 1.0
 */
@Slf4j
@RestController
@RequestMapping(value = "common")
public class CommonController {

    @PostMapping(value = "fileUpload")
    public R fileUpload(@RequestParam(value = "file") MultipartFile file, Integer type) {
        if (file == null) {
            return R.fail("没有可上传的文件");
        }
        UploadPathEnum uploadPathEnum = UploadPathEnum.get(type);
        if (uploadPathEnum == null) {
            return R.fail("不存在的上传路径类型：" + type);
        }
        return R.ok(FileUploadKit.upload(file, uploadPathEnum));
    }

    @GetMapping(value = "download")
    public void download(String filePath) {
        if (StrUtil.isBlank(filePath)) {
            throw new AdminException("不存在的文件：" + filePath);
        }
        HttpServletResponse response = HttpServletContextKit.getHttpServletResponse();
        FileUploadKit.write(response, new File(filePath));
    }

    /**
     * 使用流访问项目外部的静态文件
     */
    @GetMapping(value = "static/{uploadType}/{fileType}/{yyyyMMdd}/{filename}")
    public void staticFile(@PathVariable String uploadType, @PathVariable String fileType, @PathVariable String yyyyMMdd, @PathVariable String filename) {
        String basePath = System.getProperty("user.dir") + File.separator + Constants.BASE_USER_FILE_PATH;
        String fileUrl = basePath + "/" + uploadType + "/" + fileType + "/" + yyyyMMdd + "/" + filename;
        HttpServletResponse response = HttpServletContextKit.getHttpServletResponse();
        FileUploadKit.write(response, new File(fileUrl));
    }
}
